/*
 * Copyright (C) 2010-2011 Comcast Cable.  All Rights Reserved.
 */
package com.hercules.android.receiver.handlers.commands.call;

import com.hercules.android.receiver.AndroidReceiver;
import com.hercules.android.receiver.handlers.commands.XREViewFinderUtility;
import com.hercules.android.receiver.model.commands.XRECallCommand;
import com.hercules.android.receiver.model.commands.XRECommand;
import com.hercules.android.receiver.model.objects.XREView;

import java.util.ArrayList;
import java.util.List;

/**
 * This class represents the views finder utility that will find the views affected by a command. It implements
 * {@link XREViewFinderUtility} interface.
 * <p>
 * <b>Thread Safety:</b> Thread safe since it has no state.
 *
 * @author DanLazar, orial
 * @version 1.0
 */
public class XRECallCommandViewFinderUtility implements XREViewFinderUtility {
    /**
     * Default empty constructor.
     */
    public XRECallCommandViewFinderUtility() {
        // empty
    }

    /**
     * This method will return the affected views for the given command.
     *
     * @param receiver the receiver
     * @param command the command
     * @return a list of XREView objects; cannot be null but can be empty
     * @throws IllegalArgumentException if any parameter is incorrect
     */
    @SuppressWarnings("boxing")
    public List<XREView> getAffectedViews(XRECommand command, AndroidReceiver receiver) {
        // check arguments
        XRECallCommand callCommand = Helper.checkCommand(command);
        XREView xreView = Helper.checkReceiver(receiver, callCommand, XREView.class);

        // prepare result list
        List<XREView> result = new ArrayList<XREView>();

        // get command method
        String method = callCommand.getMethod();

        if (Helper.XREVIEW_MOD_METHODS.contains(method)) {
            if ("addChild".equals(method)) {
                // get child view that will be added to the view
                int childId = Helper.getParam(callCommand, 0, Integer.class);
                XREView childView =
                    Helper.getObject(receiver.getApplicationData().getElementsXREIdToObject().get(childId),
                        "receiver.applicationData.elementsXREIdToObject[" + childId + "]", XREView.class);

                // get the previous parent view
                XREView previousParentView = childView.getParent();
                if (previousParentView != null) {
                    result.add(previousParentView);
                }
            }

            // add current view
            result.add(xreView);
        }

        return result;
    }
}